package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 梦龙
 * @date 2023/12/7 19:52
 */

@Service
public class OrderServiceImpl implements OrderService {

    private Long ordersId;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * @description:用户下单
     * @return: com.sky.vo.OrderSubmitVO
     * @author: 梦龙
     * @time: 2023/12/7 20:20
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1. 处理各种业务异常，比如地址簿为空，购物车数据为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            //抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询用户的购物车数据
        ShoppingCart shoppingCart = new ShoppingCart();
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);

        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //2. 向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);

        orderMapper.insert(orders);
        ordersId = orders.getId();

        List<OrderDetail> orderDetails = new ArrayList<>();
        //3. 向订单明细表插入多条数据
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();//订单明细
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(ordersId);//设置当前订单明细关联的订单id
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);

        //4. 清空用户对应的购物车数据
        shoppingCartMapper.deleteByUserId(userId);
        //5. 封装为 VO 返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改
        Integer orderPaidStatus = Orders.PAID;
        Integer orderStatus = Orders.TO_BE_CONFIRMED;

        //发现没有将支付时间check_out属性赋值，在这里更新
        LocalDateTime check_out_time = LocalDateTime.now();

        orderMapper.updateStatus(orderStatus, orderPaidStatus, check_out_time, ordersId);

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向客户端浏览器推送消息
        //包含三个字段 type orderId content
        Map map = new HashMap<>();
        map.put("type", 1);//type 1 表示来单提醒，2 表示客户催单
        map.put("orderId", orders.getId());
        map.put("content", "订单号:" + outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }

    /**
     * @description:通过订单id查询订单详细数据
     * @return: com.sky.vo.OrderVO
     * @author: 梦龙
     * @time: 2023/12/10 16:47
     */
    @Override
    public OrderVO orderDetails(Long ordersId) {
        //根据订单id查询订单
        Orders orders = orderMapper.getByOrdersId(ordersId);
        //再根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(ordersId);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        orderVO.setOrderDishes(getOrderDishesStr(orders));
        return orderVO;
    }

    /**
     * @description:用户端分页查询订单
     * @return: com.sky.result.PageResult
     * @author: 梦龙
     * @time: 2023/12/10 19:55
     */
    @Override
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        //设置分页
        PageHelper.startPage(pageNum, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        if (page != null && page.size() > 0) {
            for (Orders orders : page) {
                Long ordersId = orders.getId();
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(ordersId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                orderVO.setOrderDishes(getOrderDishesStr(orders));
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * @description:取消订单，通过订单id
     * @return: void
     * @author: 梦龙
     * @time: 2023/12/10 21:07
     */
    @Override
    public void cancelOrder(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);

        //检验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //订单处于待接单状态下取消，需要进行退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //支付状态修改为：退款
            orders.setPayStatus(Orders.REFUND);
        }
        //更新订单状态，取消原因，取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void repetition(Long id) {
        //再来一单的规则是，将原订单中的商品放入购物车中
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(id);
        Long userId = BaseContext.getCurrentId();
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * @description:分页查询
     * @return: com.sky.result.PageResult
     * @author: 梦龙
     * @time: 2023/12/11 11:04
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> orderVOList = getOrderVOList(page);
        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * @description:各个状态码订单数量统计
     * @return: com.sky.vo.OrderStatisticsVO
     * @author: 梦龙
     * @time: 2023/12/11 16:18
     */
    @Override
    public OrderStatisticsVO statistic() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        //获取待接单数量 状态码为 2
        orderStatisticsVO.setToBeConfirmed(orderMapper.countStatus(Orders.TO_BE_CONFIRMED));
        //获取待派送数量 3
        orderStatisticsVO.setConfirmed(orderMapper.countStatus(Orders.CONFIRMED));
        //获取派送中数量
        orderStatisticsVO.setDeliveryInProgress(orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS));

        return orderStatisticsVO;
    }

    /**
     * @description:商家接单，通过订单id修改订单的状态改为已接单。
     * @return: void
     * @author: 梦龙
     * @time: 2023/12/11 16:29
     */
    @Override
    public void orderConfirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * @description:商家拒单
     * @return: void
     * - 商家拒单其实就是将订单状态修改为“已取消”
     * - 只有订单处于“待接单”状态时可以执行拒单操作
     * - 商家拒单时需要指定拒单原因
     * - 商家拒单时，如果用户已经完成了支付，需要为用户退款
     * @time: 2023/12/11 16:46
     */
    @Override
    public void orderRejection(OrdersRejectionDTO ordersRejectionDTO) {

        //先通过订单id查看该订单状态
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        //如果该订单状态不为待接单
        if (ordersDB == null || ordersDB.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //执行到下面说明该订单当前状态为待接单
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();

        //如果该订单已付款，那么需要改变属性payStatus为退款
        if (ordersDB.getPayStatus() == Orders.PAID) {
            //修改状态为退款
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(orders);

    }

    /**
     * @description:通过订单id取消订单
     * @return: void
     * @author: 梦龙
     * @time: 2023/12/11 21:49
     */
    @Override
    public void orderCancel(OrdersCancelDTO ordersCancelDTO) {
        //取消订单其实就是将订单状态修改为 已取消
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());
        //商家取消订单时需要指定原因
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        //商家取消订单时，如果用户已支付，需要进行退款
        if (ordersDB.getPayStatus() == Orders.PAID) {
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(orders);
    }

    /**
     * @description:通过订单id将订单状态设置为派送中，状态码为4
     * @return: void
     * @author: 梦龙
     * @time: 2023/12/11 22:10
     */
    @Override
    public void orderDelivery(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        //判断当前订单状态是否为待派送
        if (ordersDB == null || ordersDB.getStatus() != Orders.CONFIRMED) {
            //如果不是则抛出异常交给全局异常处理器
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     * @description:完成订单，通过订单id 只有状态为派送中的订单才能完成订单
     * @return: void
     * @author: 梦龙
     * @time: 2023/12/11 22:21
     */
    @Override
    public void orderComplete(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        //判断当前订单状态是否为待派送
        if (ordersDB == null || ordersDB.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            //如果不是则抛出异常交给全局异常处理器
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * @description:客户催单
     * @return: void
     * @author: 梦龙
     * @time: 2023/12/12 21:33
     */
    @Override
    public void orderReminder(Long id) {
        //根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        //校验订单是否存在
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map = new HashMap<>();
        map.put("type",2);//1 来单提醒 2 客户催单
        map.put("orderId",id);
        map.put("content","订单号:"+ordersDB.getNumber());

        //通过websocket向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * @description:返回订单详细信息，包括订单详情，订单菜品字符串
     * @return: java.util.List<com.sky.vo.OrderVO>
     * @time: 2023/12/11 11:03
     */
    public List<OrderVO> getOrderVOList(Page<Orders> page) {
        //需要将订单里面的订单详情获得，通过每个订单的订单号获得
        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> ordersList = page.getResult();
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                //订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(orders.getId());
                orderVO.setOrderDetailList(orderDetails);
                //订单菜品信息字符串
                orderVO.setOrderDishes(getOrderDishesStr(orders));
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * @description:根据订单id获取订单菜品字符串
     * @return: java.lang.String
     * @author: 梦龙
     * @time: 2023/12/11 11:03
     */
    private String getOrderDishesStr(Orders orders) {
        //查看订单菜品的详细信息
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(orders.getId());

        //将每一条订单明细信息都拼接位字符串
        List<String> orderDishList = orderDetails.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getAmount();
            return orderDish;
        }).collect(Collectors.toList());

        //将该菜品订单对应的所有菜品都拼接在一起
        return String.join("" + orderDishList);
    }


}
